﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor.ProjectWindowCallback;

public class CreateLuaFileTemplate : MonoBehaviour
{
    [UnityEditor.MenuItem("XLua/新建 Lua脚本")]
    public static void CreateLuaFileFromTemplate()
    { 
        if (!Directory.Exists(XluaEngine.LuaSrcPath))
            Directory.CreateDirectory(XluaEngine.LuaSrcPath);
        //.AssetModificationProcessor
        string path = UnityEditor.EditorUtility.SaveFilePanelInProject("新建",
            "new luaBehavior", "lua", "取个名字，直接保存", XluaEngine.LuaSrcPath);
        if (path.Length != 0)
        {
            FileInfo f = new FileInfo(path);
            string template = Application.dataPath + "/Xlua/xluaEx/Editor/Template.lua";
            string text = File.ReadAllText(template);
            string fileName = f.Name.Replace(f.Extension,"").Replace(" ","");
            text = Regex.Replace(text, "#NAME#",fileName);
            text = Regex.Replace(text, "#TIME#", DateTime.Now.ToShortDateString());
            bool encoderShouldEmitUTF8Identifier = true;
            bool throwOnInvalidBytes = false;
            UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
            bool append = false;
            path = string.Join(""+Path.DirectorySeparatorChar,new string[]
            {
                f.Directory.FullName, fileName+f.Extension
            });
            StreamWriter streamWriter = new StreamWriter(path, append, encoding);
            streamWriter.Write(text);
            streamWriter.Close();
            AssetDatabase.Refresh();
        }
    }
    
    [MenuItem("Assets/Create/Lua ", false, 91)]
    public static void CreatNewLua()
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
            ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(),
            GetSelectedPathOrFallback() + "/New Lua.lua",
            null,
            "Assets/Xlua/xluaEx/Editor/Template.lua");
    }
 
    public static string GetSelectedPathOrFallback()
    {
        string path = "Assets";
        foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
        {
            path = AssetDatabase.GetAssetPath(obj);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                path = Path.GetDirectoryName(path);
                break;
            }
        }
        return path;
    }
}
class MyDoCreateScriptAsset : EndNameEditAction
{
    public override void Action(int instanceId, string pathName, string resourceFile)
    {
        UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
        ProjectWindowUtil.ShowCreatedAsset(o);
    }
 
    internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
    {
        string fullPath = Path.GetFullPath(pathName);
        StreamReader streamReader = new StreamReader(resourceFile);
        string text = streamReader.ReadToEnd();
        streamReader.Close();
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
        text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);
        text = Regex.Replace(text, "#TIME#", DateTime.Now.ToShortDateString());
        bool encoderShouldEmitUTF8Identifier = true;
        bool throwOnInvalidBytes = false;
        UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
        bool append = false;
        StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
        streamWriter.Write(text);
        streamWriter.Close();
        AssetDatabase.ImportAsset(pathName);
        return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
    }
 
}    
